﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenQA.Selenium;


namespace AutoTestingFramework.Core
{
    public abstract class PageObjectModelBase
    {
        private Uri _uri = null;

        public Uri Uri
        {
            get { return _uri; }
            set { _uri = value; }
        }

        /// <summary>
        /// all the inheritor should override this value
        /// </summary>
        protected string Url
        {
            get
            {
                return _uri.ToString();
            }
            set
            {
                // in case developer didn't give any value.
                if (string.IsNullOrWhiteSpace(value))
                {
                    value += "/";
                }
                _uri = value.StartsWith(@"/")
                    ? new Uri(value, UriKind.Relative)
                    : new Uri(value, UriKind.Absolute);
            }
        }
    }

    public abstract class PageObjectModelBase<T> : PageObjectModelBase where T : PageObjectModelBase
    {
        private TestBase _testObject { get; set; }

        public PageObjectModelBase(TestBase testObject)
        {
            this._testObject = testObject;
        }

        public T Go()
        {
            if (Uri == null)
            {
                throw new NotImplementedException("This page cannot navigated to this uri or the Uri property is not set.");
            }
            return this.Go(Uri);
        }
        public T Go(Uri url)
        {
            var broswer = _testObject.webBroswer;

            if (string.IsNullOrWhiteSpace(_testObject.BaseUrl))
                throw new NotImplementedException("This page cannot navigated to this uri or the BaseUrl property is not set.");

            var currentUrl = new Uri(_testObject.BaseUrl);
            var baseUrl = currentUrl.GetLeftPart(System.UriPartial.Authority);
            if (!url.IsAbsoluteUri)
            {
                url = new Uri(new Uri(baseUrl), url.ToString());
            }
            broswer.Navigate().GoToUrl(url);

            return this as T;
        }
    }
}
